﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using ViewLayer.Studies;
using ControllerLayer.MainView;
using ControllerLayer.PatientInformation;
using ControllerLayer.Reports;
using Microsoft.VisualBasic.PowerPacks;
using MedicalDictationView;
using ModelLayer.Login;
using ViewLayer.PatientInformationView;
using ControllerLayer.Login;
using ControllerLayer.ServiceReferenceCCW;


namespace ViewLayer.MainView
{
    public partial class MainView : Form
    {
        public static int lastTimeLog=1;
        public User user = User.Instance;
        public int currentDataRepeaterItemIndex;
        public string initialAccessionNumber;
        
        public MainView(string accessionNumber, string pid)
        {
            InitializeComponent();
            this.initialAccessionNumber = accessionNumber;
            MainViewController.currentPID = pid;
            try
            {
                this.patientProfile_TableAdapter.Fill(this.patientInformationDataSet.PatientProfile_, MainViewController.currentPID);
                this.visit_TableAdapter.Fill(this.visitDataSet.Visit_, new System.Guid(PatientInformationViewController.GetPatientOIDByPID(MainViewController.currentPID)));
                dataRepeater1.DataSource = this.visitDataSet.Visit_;
                MainViewController.loadFlag = true;
                MainViewController.userLogOutFlag = true;
            }
            catch (System.Exception ex)
            {
                MainViewController.loadFlag = false;
            }
        }

        private int SetIndexForAccessionNumber()
        {
            int index;
            for (index = 0; index < dataRepeater1.ItemCount; index++)
            {
                if (dataRepeater1.CurrentItem.Controls["accessionNumberLbl"].Text == this.initialAccessionNumber)
                {
                    MainViewController.selectedProcedureTypeName = dataRepeater1.CurrentItem.Controls["tipoDeProcedimientoLbl"].Text;
                    this.dataRepeater1_CurrentItemIndexChanged(null, null);
                    return index;
                }
                try
                {
                    dataRepeater1.CurrentItemIndex++;
                }
                catch
                {
                    MessageBox.Show(null,"Accession Number no encontrado","Advertencia",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    dataRepeater1.CurrentItemIndex = 0;
                    this.dataRepeater1_CurrentItemIndexChanged(null, null);
                    return 0;
                }
            }
            return 0;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            SearchView searchView = new SearchView(true);
            searchView.ShowDialog();
            if (!MainViewController.userLogOutFlag)
                this.Close();
        }

        private void MainView_Load(object sender, EventArgs e)
        {
            if (!MainViewController.loadFlag)
            {
                SearchView searchView = new SearchView(false);
                searchView.ShowDialog();
                if (!MainViewController.userLogOutFlag)
                    this.Close();
            }
            else
            {
                string var = Environment.GetEnvironmentVariable(ConfigurationManager.AppSettings["UserVariable"].ToString(),EnvironmentVariableTarget.User);

                if (var == null)
                {
                    if (InitializationOfLogin(1, ""))
                    {
                        Environment.SetEnvironmentVariable(ConfigurationManager.AppSettings["UserVariable"].ToString(), user.getName(), EnvironmentVariableTarget.User);
                    }
                    else
                    {
                        this.Close();
                        Application.Exit();
                    }
                }
                else
                {
                    string userName = Environment.GetEnvironmentVariable(ConfigurationManager.AppSettings["UserVariable"].ToString(), EnvironmentVariableTarget.User);
                    user = LoginController.getUserInstanceFromUserName(userName);
                }

                if (ControllerLayer.Login.LoginController.exit == false)
                {
                    MainViewController.nameLabel = (ToolStripLabel) toolStrip.Items["userLabel"];
                    MainViewController.nameLabel.Text = "Usuario: " + user.getName();

                    this.patientProfileContactPerson_TableAdapter.Fill(this.patientInformationDataSet.PatientProfileContactPerson_);

                    this.SetIndexForAccessionNumber();

                    MainViewController.LoadFullnameLabel(labelFullName, familyName_Label1, givenName_Label1);
                    this.Text += MainViewController.currentPatientName;
                    MainViewController.LoadUpperDetailInformation(labelAgeSex, dateOfBirth_Label1, sex_Label1);

                    panelChild.Controls.Add(new StudiesViewControl());

                    lastTimeLog = 2;
                }
            }
        }

        public bool InitializationOfLogin(int timeLog,string txt)
        {
            while (ControllerLayer.Login.LoginController.exit == false 
                && ControllerLayer.Login.LoginController.autentication==false)
            {
                Login.LoginView login = new Login.LoginView(timeLog, txt);
                login.ShowDialog();
            }
            if (ControllerLayer.Login.LoginController.exit == true)
            {
                return false;
            }
            if (ControllerLayer.Login.LoginController.autentication == true)
            {
                   return true;
            }           
             return false; 
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            panelChild.Controls.Clear();
            MainViewController.changeView = false;
       
             switch (tabControl.SelectedIndex)
            {
                case 0:
                    panelChild.Controls.Add(new StudiesViewControl());
                    break;
                case 1: 
                    panelChild.Controls.Add(new PatientInfoViewControl(MainViewController.currentPID));
                    tabPagePatientInfo.Controls.Add(new PatientNoteControl(PatientInformationViewController.GetPatientOIDByPID(MainViewController.currentPID)));
                    break;
            }    
        }

        private void dataRepeater1_CurrentItemIndexChanged(object sender, EventArgs e)
        {
            panelChild.Controls.Clear();
            MainViewController.changeView = false;
            MainViewController.selectedProcedureTypeName = dataRepeater1.CurrentItem.Controls["tipoDeProcedimientoLbl"].Text;
            MainViewController.currentAccessionNumber = dataRepeater1.CurrentItem.Controls["accessionNumberLbl"].Text;
            dataRepeater1.CurrentItem.Focus();

            foreach (DataRepeaterItem item in dataRepeater1.Controls)
                foreach (Control c in item.Controls)
                    c.ForeColor = Color.Black;

            foreach (Control c in dataRepeater1.CurrentItem.Controls)
                    c.ForeColor = Color.RoyalBlue;

            panelChild.Controls.Add(new StudiesViewControl());               
        }

        private void dataRepeater1_DrawItem(object sender, Microsoft.VisualBasic.PowerPacks.DataRepeaterItemEventArgs e)
        {
            if ((e.DataRepeaterItem.ItemIndex % 2) != 0)
            {
                e.DataRepeaterItem.BackColor = Color.AliceBlue;
            }
            else
            {
                e.DataRepeaterItem.BackColor = Color.White;
            }
        }

        private void MainView_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(MainViewController.userLogOutFlag)
                Environment.SetEnvironmentVariable(ConfigurationManager.AppSettings["UserVariable"].ToString(), null, EnvironmentVariableTarget.User);
        }

        private void toolStripButtonExit_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show(null, "¿Esta seguro que desea salir de MedSpeech?", "Salir", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
            {
                this.Close();
            }
        }
    }
}
